import CommonModal from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import { tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { forwardRef, useDeferredValue, useEffect, useState } from 'react'
import { getAggrOptions } from '@/api/shoppingCart.ts'
import { Checkbox, Radio } from 'antd'

const EditPolymerizeScope = forwardRef(
  (
    props: {
      itemId: string
      done: (() => void) | undefined
      polymerizeInfo: {
        label: string
        id: string
      }
      disabled?: boolean
    },
    ref
  ) => {
    const [polymerizeList, setPolymerizeList] = useState([])
    const [polymerizeOptions, setPolymerizeOptions] = useState([])

    const notEditable = !!props.disabled

    useEffect(() => {
      if (props.polymerizeInfo.id)
        getAggrOptions(props.polymerizeInfo.id).then((res) => {
          setPolymerizeList([])
          setPolymerizeOptions(res ?? [])
        })
    }, [props.polymerizeInfo.id])

    const deferredValue = useDeferredValue(polymerizeOptions)

    return (
      <CommonModal
        ref={ref}
        title={props.polymerizeInfo.label}
        onOpen={() => {
          const localData = tempData('polymerizeList')
          setPolymerizeList(localData?.[props.polymerizeInfo.id] ?? [])
        }}
        onOk={() => {
          if (notEditable) return
          props.done?.()
          const data = tempData('polymerizeList') ?? {}
          tempData({
            polymerizeList: {
              ...data,
              [props.polymerizeInfo.id]: polymerizeList
            }
          })
        }}
        onCancel={() => {
          console.log('取消')
        }}>
        <div className="py-4">
          <Radio
            disabled={notEditable}
            checked={!polymerizeList.length}
            onClick={() => {
              setPolymerizeList([])
            }}>
            不限
          </Radio>
        </div>
        <div className="flex flex-col gap-4 overflow-auto max-h-65vh">
          {deferredValue.map((polymerize) => (
            <div key={polymerize}>
              <Checkbox
                disabled={notEditable}
                key={polymerize}
                checked={polymerizeList.includes(polymerize)}
                onChange={(e) => {
                  setPolymerizeList((prevState) => {
                    if (e.target.checked) {
                      return prevState.concat(polymerize)
                    } else {
                      return prevState.filter((it) => it !== polymerize)
                    }
                  })
                }}>
                <p>{polymerize}</p>
              </Checkbox>
            </div>
          ))}
        </div>
      </CommonModal>
    )
  }
)

export default EditPolymerizeScope
